//
//  IDTools.m
//  EMMApp
//
//  Created by QuDavid on 15/9/11.
//  Copyright (c) 2015年 XJH.COM. All rights reserved.
//

#import "IDTools.h"
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import <ifaddrs.h>
#import <arpa/inet.h>


@implementation NSDictionary(MyExtend)
- (id)objectAtPath:(NSString *)path{
    NSString *separator = @"/";
    path = [path stringByReplacingOccurrencesOfString:@"." withString:@"/"];
    
    NSString *	keyPath = [path stringByReplacingOccurrencesOfString:separator withString:@"."];
    NSRange		range = NSMakeRange( 0, 1 );
    
    if ( [[keyPath substringWithRange:range] isEqualToString:@"."] )
    {
        keyPath = [keyPath substringFromIndex:1];
    }
    
    NSObject * result = [self valueForKeyPath:keyPath];
    return (result == [NSNull null]) ? nil : result;
}
@end

@implementation IDTools




+ (void)addToLocalCart:(NSString *) goodsId qty:(NSString *) mqty
{
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    
    NSMutableDictionary *mids = (NSMutableDictionary *)[userdf valueForKey:@"local_cart_goods_ids"];
    NSMutableDictionary *midsTmp = nil;
    if (mids==nil) {
        midsTmp = [[NSMutableDictionary alloc] init];
    }else{
        midsTmp = [[NSMutableDictionary alloc] initWithDictionary:mids];
    }
    
    if ([midsTmp objectForKey:goodsId]!=nil) {
        [midsTmp setValue:[NSString stringWithFormat:@"%d",[mqty intValue] + [[midsTmp objectForKey:goodsId] intValue]] forKey:goodsId];
    }else{
        [midsTmp setValue:mqty forKey:goodsId];
    }
    
    [userdf setObject:midsTmp forKey:@"local_cart_goods_ids"];
    
    
    [userdf synchronize];
}

+ (void)clearLocalCart
{
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    
    [userdf setObject:[[NSMutableDictionary alloc] init] forKey:@"local_cart_goods_ids"];
    
    [userdf synchronize];
}

+ (void)removeLocalCart:(NSArray *) goodsIds
{
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    
    NSMutableDictionary *mids = (NSMutableDictionary *)[userdf valueForKey:@"local_cart_goods_ids"];
    NSMutableDictionary *midsTmp = nil;
    if (mids==nil) {
        midsTmp = [[NSMutableDictionary alloc] init];
    }else{
        midsTmp = [[NSMutableDictionary alloc] initWithDictionary:mids];
    }
    
    for (int i =0; i<goodsIds.count; i++) {
        NSString *delGoodsId = [goodsIds objectAtIndex:i];
        if ([midsTmp objectForKey:delGoodsId]!=nil) {
            [midsTmp removeObjectForKey:delGoodsId];
        }
    }
    
    [userdf setObject:midsTmp forKey:@"local_cart_goods_ids"];
    
    [userdf synchronize];
}

+ (void)addToLocalCart:(NSString *) goodsId qty:(NSString *) mqty oldGoodsId:(NSString *) oldGoodsId
{
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    
    NSMutableDictionary *mids = (NSMutableDictionary *)[userdf valueForKey:@"local_cart_goods_ids"];
    NSMutableDictionary *midsTmp = nil;
    if (mids==nil) {
        midsTmp = [[NSMutableDictionary alloc] init];
    }else{
        midsTmp = [[NSMutableDictionary alloc] initWithDictionary:mids];
    }
    if ([midsTmp objectForKey:oldGoodsId]!=nil) {
        [midsTmp removeObjectForKey:oldGoodsId];
    }
    if ([midsTmp objectForKey:goodsId]!=nil) {
        [midsTmp setValue:[NSString stringWithFormat:@"%d",[mqty intValue] + [[midsTmp objectForKey:goodsId] intValue]] forKey:goodsId];
    }else{
        [midsTmp setValue:mqty forKey:goodsId];
    }
    
    [userdf setObject:midsTmp forKey:@"local_cart_goods_ids"];
    
    
    [userdf synchronize];
}

+ (NSMutableDictionary *)getLocalCart
{
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    
    NSMutableDictionary *mids = (NSMutableDictionary *)[userdf valueForKey:@"local_cart_goods_ids"];
    if (mids==nil) {
        mids = [[NSMutableDictionary alloc] init];
    }
    
    return mids;
}

+ (NSString *)getLocalCartCount
{
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    
    NSMutableDictionary *mids = (NSMutableDictionary *)[userdf valueForKey:@"local_cart_goods_ids"];
    if (mids==nil) {
        mids = [[NSMutableDictionary alloc] init];
    }
    
    int mqtys = 0;
    
    for (int i=0; i<mids.count; i++) {
        NSString *qty = [mids objectForKey:[[mids allKeys] objectAtIndex:i]];
        mqtys += [qty intValue];
    }
    
    return [NSString stringWithFormat:@"%d",mqtys];
}


+ (void)logout
{
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    [userdf removeObjectForKey:@"userNameId"];
    [userdf removeObjectForKey:@"token"];
    [userdf removeObjectForKey:@"isLoginSuc"];
    [userdf removeObjectForKey:@"userName"];
    [userdf removeObjectForKey:@"userMobile"];
    [userdf synchronize];
}

// Get IP Address
+ (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}



+ (NSString *)devId
{
    return [NSString stringWithFormat:@"%@|2|%@|%@", [IDTools idString2]==nil?[IDTools idString]:[IDTools idString2], [[UIDevice currentDevice] systemVersion], [IDTools firstSetupDate]];
}

+ (NSString *)devId2
{
    return [NSString stringWithFormat:@"%@|2|%@|%@", [IDTools idString], [[UIDevice currentDevice] systemVersion], [IDTools firstSetupDate]];
    //NSString *str = @"";
    //return str;
}

+ (NSInteger)timeout
{
    return 30;
}

+ (NSString*)idString2
{
    NSString *udid = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken123"];
    NSLog(@"DeviceToken123 : %@", udid);
    if ([NSString isStringEmpty2:udid]) {
        udid = @"";
    }
    return udid;
}

+ (NSString*)idString
{
    NSString *udid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"];
    if (!udid) {
        
        NSString *sysVersion = [UIDevice currentDevice].systemVersion;
        CGFloat version = [sysVersion floatValue];
        
        if (version >= 7.0) {
            udid = [IDTools _UDID_iOS7];
        }
        else if (version >= 2.0) {
            udid = [IDTools uuid];
        }
        
        [[NSUserDefaults standardUserDefaults] setValue:udid forKey:@"uuid"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    return udid;
}

+ (void)setValueStr:(NSString *)valstr keyStr:(NSString *)keystr
{
    [[NSUserDefaults standardUserDefaults] setValue:valstr forKey:keystr];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString*)apiUrl
{
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"api21"];
    if (!str) {
        
        str = @"http://www.admore.cn:10002/vas-openapi/api/";
        
        [[NSUserDefaults standardUserDefaults] setValue:str forKey:@"api"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    return str;
}

+ (NSString *)dateToString:(NSDate *)date
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    
    return dateString;
}

+ (NSString *)dateToQueryString:(NSDate *)date
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    
    return dateString;
}

+ (NSString *)dateToQueryString2:(NSDate *)date
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    
    return dateString;
}

+ (NSDate *)dateFromString:(NSString *)date
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *dateString = [dateFormatter dateFromString:date];
    
    
    return dateString;
}

+ (NSDate *)dateFromString2:(NSString *)date
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *dateString = [dateFormatter dateFromString:date];
    
    
    return dateString;
}

+ (NSString*)firstSetupDate
{
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"setupdate"];
    if (!str) {
        
        NSDate *date = [NSDate date];
        str = [IDTools dateToString:date];
        
        [[NSUserDefaults standardUserDefaults] setValue:str forKey:@"setupdate"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    return str;
}

+ (NSString *)getJson:(NSString *)jsonString baseKey:(NSString *)baseKey
{
    NSObject *json = [jsonString objectFromJSONString];
    if(json == nil)
    {
        NSLog(@"Json string is invalid.");
        return nil;
    }
    if([json isKindOfClass:[NSDictionary class]]){
        if(![baseKey isEqualToString:@""] && baseKey != nil){
            NSDictionary *dict = [(NSDictionary *)json objectAtPath:baseKey];
            return [dict JSONString];
        }
    }
    
    return jsonString;
}

/*
 * iOS 6.0
 * use wifi's mac address
 */
+ (NSString*)_UDID_iOS6
{
    return [IDTools getMacAddress];
}

+ (NSString*) uuid
{
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}

+ (NSString *)deviceToken
{
    return [IDTools idString2];
}

/*
 * iOS 7.0
 * Starting from iOS 7, the system always returns the value 02:00:00:00:00:00
 * when you ask for the MAC address on any device.
 * use identifierForVendor
 */
+ (NSString*)_UDID_iOS7
{
    return [[UIDevice currentDevice].identifierForVendor UUIDString];
}


+ (NSDictionary *)jsonStringToDict:(NSString *)aStr
{
    NSData *data = [aStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return dict;
}

+ (NSArray *)jsonStringToArray:(NSString *)aStr
{
    NSData *data = [aStr dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return arr;
}

+ (id)jsonStrToObjc:(NSString *)jsonStr method:(NSString *)method
{
    @try {
        NSDictionary *dict = [IDTools jsonStringToDict:jsonStr];
        
        id myObj = [EMMApiUtils respWithSuccess:dict method:method canNewClass:YES];
        
        return myObj;
    }
    @catch (NSException *exception) {
        NSLog(@"%@", exception);
    }
    @finally {
        
    }
    
    return nil;
}


+ (id)json2objc:(NSString *)aStr
{
    NSData *data = [aStr dataUsingEncoding:NSUTF8StringEncoding];
    return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}

#pragma mark -

/**
 *  允许中文和字母
 *
 *  @param string
 *
 *  @return
 */
+ (BOOL)checkName:(NSString *)string
{
    if ([string isEqualToString:@"，"]||[string isEqualToString:@"➋"]||[string isEqualToString:@"➌"]||[string isEqualToString:@"➍"]||[string isEqualToString:@"➎"]||[string isEqualToString:@"➏"]||[string isEqualToString:@"➐"]||[string isEqualToString:@"➑"]||[string isEqualToString:@"➒"]) {
        return YES;
        
    }
    NSString *Regex = @"^[A-Za-z\u4e00-\u9fa5]*$";
    NSPredicate *Test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [Test evaluateWithObject:string];
}

/**
 *  检查是否是数字和小数点
 *
 *  @param string
 *  @param text
 *
 *  @return
 */
+ (BOOL)checkNumber:(NSString *)string WithTextFieldText:(NSString*)text{
    
    
    NSCharacterSet*cs;
    cs =[[NSCharacterSet characterSetWithCharactersInString:@"0123456789." ]invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    
    
    if ([text rangeOfString:@"."].length>0) {
        if ([string isEqualToString:@"."]) {
            return NO;
        }
    }
    return basicTest;
    
}

/**
 *  检查匹配由数字和26个英文字母组成的字符串
 *
 *  @param string
 *
 *  @return
 */
+ (BOOL)checkStringNumbersWithlettersWithString:(NSString*)string{
    NSString *regex=@"^[A-Za-z0-9]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![predicate evaluateWithObject:string]) {
        return YES;
    }
    return NO;
}

/**
 *  检查含有数字标点
 *
 *  @param string
 *
 *  @return
 */
+ (BOOL)checkShuZiWithBiaoDianWithString:(NSString*)string
{
    NSString *regex=@"^[A-Za-z /\u4e00-\u9fa5]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![predicate evaluateWithObject:string]) {
        return YES;
    }
    return NO;
    
}


#pragma mark -
#pragma mark Helper Method for Get Mac Address

// from http://stackoverflow.com/questions/677530/how-can-i-programmatically-get-the-mac-address-of-an-iphone
+ (NSString *)getMacAddress
{
    int                 mgmtInfoBase[6];
    char                *msgBuffer = NULL;
    size_t              length;
    unsigned char       macAddress[6];
    struct if_msghdr    *interfaceMsgStruct;
    struct sockaddr_dl  *socketStruct;
    NSString            *errorFlag = nil;
    
    // Setup the management Information Base (mib)
    mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
    mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
    mgmtInfoBase[2] = 0;
    mgmtInfoBase[3] = AF_LINK;        // Request link layer information
    mgmtInfoBase[4] = NET_RT_IFLIST;  // Request all configured interfaces
    
    // With all configured interfaces requested, get handle index
    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
        errorFlag = @"if_nametoindex failure";
    else
    {
        // Get the size of the data available (store in len)
        if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
            errorFlag = @"sysctl mgmtInfoBase failure";
        else
        {
            // Alloc memory based on above call
            if ((msgBuffer = malloc(length)) == NULL)
                errorFlag = @"buffer allocation failure";
            else
            {
                // Get system information, store in buffer
                if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
                    errorFlag = @"sysctl msgBuffer failure";
            }
        }
    }
    
    // Befor going any further...
    if (errorFlag != NULL)
    {
        NSLog(@"Error: %@", errorFlag);
        if (msgBuffer) {
            free(msgBuffer);
        }
        
        return errorFlag;
    }
    
    // Map msgbuffer to interface message structure
    interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
    
    // Map to link-level socket structure
    socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
    
    // Copy link layer address data in socket structure to an array
    memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
    
    // Read from char array into a string object, into traditional Mac address format
    NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                                  macAddress[0], macAddress[1], macAddress[2],
                                  macAddress[3], macAddress[4], macAddress[5]];
    NSLog(@"Mac Address: %@", macAddressString);
    
    // Release the buffer memory
    free(msgBuffer);
    
    return macAddressString;
}

+ (NSDate *)getTheDate:(NSDate *)theDate numMonth:(NSInteger)num
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = nil;
    comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:theDate];
    
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setYear:0];
    [adcomps setMonth:num];
    [adcomps setDay:0];
    
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:theDate options:0];

    
    return newdate;
}

#pragma mark - 时间戳

+ (NSString *)TimerString:(float)fTimer
{
    int iHour = fTimer / 3600;
    float fMinute = fTimer - (iHour * 3600);
    int iMinute = fMinute / 60;
    int iSecond = fMinute - (iMinute * 60);
    
    if (iHour != 0)
    {
        return [NSString stringWithFormat:@"%.2d:%.2d:%.2d", iHour, iMinute, iSecond];
    }
    else
    {
        return [NSString stringWithFormat:@"%.2d:%.2d", iMinute, iSecond];
    }
    return nil;
}

+ (NSString *)GetCurrentDate
{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *date = [[NSString alloc] initWithString:[dateFormatter stringFromDate:now]];
    return date;
}
+ (NSString *)GetPureCurrentDate
{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMdd";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *date = [[NSString alloc] initWithString:[dateFormatter stringFromDate:now]];
    return date;
}

+ (NSString *)GetCurrentTimeForFileSuffix
{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd_HH-mm-ss_SSS";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *date = [[NSString alloc] initWithString:[dateFormatter stringFromDate:now]];
    return date;
}

+ (NSString *)GetCurrentTimeStr
{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *date = [[NSString alloc] initWithString:[dateFormatter stringFromDate:now]];
    return date;
}

+ (NSDate *)GetCurrentTime
{
    NSDate *now = [NSDate date];
    return now;
}

+ (NSTimeInterval)GetCurrentGMTTime
{
    NSDate *now = [NSDate date];
    NSTimeInterval nowTime = [now timeIntervalSince1970];
    return nowTime;
}

+ (NSTimeInterval)GetCurrentMillisecondGMTTime
{
    NSTimeInterval nowTime = [self GetCurrentGMTTime] * 1000;
    NSTimeInterval _nowTime = nowTime/1000;
    return _nowTime;
}

+ (NSString *)GetCurrentTimeStringWithFormat:(NSString *)format
{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = format;
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *date = [[NSString alloc] initWithString:[dateFormatter stringFromDate:now]];
    return date;
}

+ (NSString*)setMonth
{
    NSDateFormatter* nowTime = [[NSDateFormatter alloc]init];
    [nowTime setDateFormat:@"y-MM"];
    NSString* month = [NSString stringWithFormat:@"%@",[nowTime stringFromDate:[NSDate date]]];
    return month;
}

+ (NSString*)setLastMonth:(NSString *)monthStr
{
    NSString *tempY = [monthStr substringToIndex:4];
    NSString *tempM = [monthStr substringFromIndex:5];
    
    int tmpY = [tempY intValue];
    int tmpM = [tempM intValue];
    
    if (1 == tmpM) {
        tmpY--;
        tmpM = 12;
    }
    else {
        tmpM--;
    }
    NSString* lastMonth = [NSString stringWithFormat:@"%d-%02d",tmpY,tmpM];
    return lastMonth;
}

+ (NSDate *)GetDateWithTimeString:(NSString *)time
{
    if (time == nil)
    {
        return nil;
    }
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:time];
    return date;
}

+ (NSDate *)GetDateWithTimeString:(NSString *)time format:(NSString *)format
{
    if (time == nil){
        return nil;
    }
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    NSDate *date = [formatter dateFromString:time];
    return date;
}
+ (NSString *)getDateStringTimeInterval:(unsigned long long)timeInterval
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [formatter stringFromDate:date];
}

+ (NSDate *)GetDateWithGMT:(unsigned long long)timeInterval
{
    return [NSDate dateWithTimeIntervalSince1970:timeInterval];
}

+ (NSString *)GetStringWithDate:(NSDate *)time
{
    if (time == nil)
    {
        return @"";
    }
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *date = [formatter stringFromDate:time];
    return date;
}

+ (NSString *)GetStringWithDate:(NSDate *)time format:(NSString *)format
{
    if (time == nil)
    {
        return @"";
    }
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    NSString *date = [formatter stringFromDate:time];
    return date;
}

+ (NSString *)GetLocalStringWithDate:(NSDate *)time format:(NSString *)format
{
    
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [NSLocale currentLocale];
    
    [fmt setDateStyle:NSDateFormatterShortStyle];
    [fmt setTimeStyle:NSDateFormatterShortStyle];
    //    if (format) {
    //        fmt.dateFormat = format;
    //    }else{
    //        fmt.dateFormat = @"yyyy-MM-dd HH:mm a";
    //    }
    NSString* dateString = [fmt stringFromDate:time];
    return dateString;
}

+ (NSString *)GetStringHourWithDate:(NSDate *)time
{
    if (time == nil)
    {
        return @"";
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"h:mm a"];
    NSString *date = [formatter stringFromDate:time];
    NSString *ret = @"  ";
    if (date != nil)
    {
        ret = [[NSString alloc] initWithString:date];
    }
    
    return ret;
}

+ (NSDate *)ConvertDatetoLocal:(NSDate *)date
{
    if (date == nil)
    {
        return nil;
    }
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    return localeDate;
}
+ (NSDate *)ConvertGMTTimeToLocal:(NSTimeInterval)timeinterval
{
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSDate *date = [IDTools GetDateWithGMT:timeinterval];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    return localeDate;
}

+(NSString *)getFormateTimeWithDate:(NSDate *)timeDate
{
    if (timeDate == nil)
    {
        return @" ";
    }
    NSDate *currentlocaleDate           = [IDTools GetCurrentTime];  // 当前时间
    
    long long  todayInterval            = [currentlocaleDate timeIntervalSince1970];
    currentlocaleDate                   = [currentlocaleDate dateByAddingTimeInterval:-(todayInterval%86400)];
    todayInterval                       = [currentlocaleDate timeIntervalSince1970];
    NSDateFormatter *dateFormatter      = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
    NSString *dateStr                   = [dateFormatter stringFromDate:timeDate];
    
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *date                        = [dateFormatter dateFromString:dateStr]; //要转换的时间
    long long  dateInterval             = [date timeIntervalSince1970];
    long long intervalDay                     = (long long)(todayInterval - (dateInterval-dateInterval%86400))/86400;
    
    if (intervalDay < 1 && intervalDay >= 0) //今天
    {
        todayInterval       = [[IDTools GetCurrentTime] timeIntervalSince1970];
        int todayHour       = (long long)todayInterval%86400/3600;
        int dateHour        = (long long)dateInterval%86400/3600;
        int intervalHour    = todayHour - dateHour;
        long minInterval     = (todayInterval - dateInterval)/(long)60;
        if (intervalHour == 0 || (intervalHour == 1 && minInterval < 60))  // 1小时之内
        {
            NSString *timeStr = nil;
            if (minInterval <= 0)
            {
                return NSLocalizedString(@"Now", nil);
            }
            else
            {
                timeStr   = [NSString stringWithFormat:@"%ld",minInterval];
            }
            if (minInterval > 1) {
                timeStr = [NSString stringWithFormat:@"%@ %@",timeStr,NSLocalizedString(@"mins ago", nil)];
            }else{
                timeStr = [NSString stringWithFormat:@"%@ %@",timeStr,NSLocalizedString(@"min ago", nil)];
            }
            
            return NSLocalizedString(timeStr, nil);
        }
        return [[self class] GetStringHourWithDate:timeDate];
    }
    if(intervalDay < 2)// 昨天
    {
        return NSLocalizedString(@"Yesterday", nil);
    }
    
    long weekInterval          = (long)(todayInterval - dateInterval)/(long)86400/(long)7;
    if (weekInterval == 0)//一周之内
    {
        [dateFormatter setDateFormat:@"EEE, MMM d, yy"];
        NSString *str   = [dateFormatter stringFromDate:date];
        NSArray *array  = [str componentsSeparatedByString:@","];
        str = [array objectAtIndex:0];
        return NSLocalizedString(str, nil);
    }
    return [dateStr substringToIndex:10];
}
+ (NSString *)getTimeStrWithDate:(NSDate *)timeDate
{
    if (timeDate == nil)
    {
        return @"";
    }
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd HH:mm"];
    NSString *date = [[formatter stringFromDate:timeDate] copy];
    return date;
}


+ (NSString *)amStringWithStr:(NSString *)dateStr
{
    if (dateStr == nil){
        return @"";
    }
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    if ([dateStr length] > 11) {
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }else{
        [formatter setDateFormat:@"MM-dd HH:mm"];
    }
    
    NSDate *date = [formatter dateFromString:dateStr];
    [formatter setDateFormat:@"MM-dd h:mm a"];
    NSString *str = [formatter stringFromDate:date];
    if (str) {
        return str;
    }
    return dateStr;
}

+ (NSString *)getShopItemHtml5:(NSString *)bodystr
{
    NSString *html =[NSString stringWithFormat:@"<html><head>\
                     <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> \
                     <style>img{     max-width: %@ ; \
                     width:auto; height:auto;}</style>\
                     </head>\
                     <body>%@</body></html>", @"100%", bodystr];
    return html;
}

+ (NSString *)getShopItemHtml5_pc:(NSString *)bodystr
{
    NSString *html =[NSString stringWithFormat:@"<html><head>\
                     <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"> \
                     <style>img{     max-width: %@ ; \
                     width:auto; height:auto;}</style>\
                     </head>\
                     <body>%@</body></html>", @"100%", bodystr];
    return html;
}

+ (UIButton *)creatButtonWithFrame:(CGRect)frame target:(id)target sel:(SEL)sel tag:(NSInteger)tag image:(NSString *)name title:(NSString *)title{
    UIButton *button = nil;
    if (name) {
        
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
        if (title) {
            [button setTitle:title forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
        }
        
    }else if (title) {
        button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setTitle:title forState:UIControlStateNormal];
    }
    
    button.frame = frame;
    button.tag = tag;
    [button addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    return button;
}

+ (BOOL)isEmptyString:(NSString *)string
{
    if([string length]==0){                  //string is empty or nil
        return YES;
    }else if([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0){
        //string is all whitespace
        return YES;
    }
    return NO;
}

+ (NSString *)trimEmpty:(NSString *)string
{
    return [IDTools isEmptyString:string]?@"":[string trim];
}

+ (NSString *)stringByTrimming:(NSString *)string
{
    if (string) {
        NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\""];
        NSString *trimmedString = [string stringByTrimmingCharactersInSet:set];
        NSCharacterSet *whitespace = [NSCharacterSet  whitespaceAndNewlineCharacterSet];
        trimmedString = [string stringByTrimmingCharactersInSet:whitespace];
        return trimmedString;
    } else {
        return @"";
    }
    
}

+ (NSString *)userNameStringByTrimming:(NSString *)string
{
    if (string) {
        NSCharacterSet *whitespace = [NSCharacterSet  whitespaceAndNewlineCharacterSet];
        NSString *trimmedString = [string stringByTrimmingCharactersInSet:whitespace];
        return trimmedString;
    } else {
        return @"";
    }
}

+ (BOOL)isContainsEmoji:(NSString *)string
{
    __block BOOL isEomji = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         
         // surrogate pair
         
         if (0xd800 <= hs && hs <= 0xdbff) {
             
             if (substring.length > 1) {
                 
                 const unichar ls = [substring characterAtIndex:1];
                 
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     
                     isEomji = YES;
                     
                 }
                 
             }
             
         } else if (substring.length > 1) {
             
             const unichar ls = [substring characterAtIndex:1];
             
             if (ls == 0x20e3) {
                 
                 isEomji = YES;
                 
             }
             
         } else {
             
             // non surrogate
             
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 
                 isEomji = YES;
                 
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 
                 isEomji = YES;
                 
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 
                 isEomji = YES;
                 
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 
                 isEomji = YES;
                 
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 
                 isEomji = YES;
                 
             }
             
         }
         
     }];
    
    return isEomji;
}

+ (BOOL)isEmojiKeyboard:(UITextField *)textField string:(NSString *)string
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_7_0
    NSLog(@"键盘模式：%@", [UITextInputMode currentInputMode] primaryLanguage]);
    // ios7.0以前
    if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString:@"emoji"]) {
        return YES;
    }
#else
    if ([textField isFirstResponder])
    {
        NSLog(@"键盘模式：%@", [textField.textInputMode primaryLanguage]);
        // ios7.0以后
        if ([[textField.textInputMode primaryLanguage] isEqualToString:@"emoji"]  || ![[textField textInputMode] primaryLanguage]) {
            return YES;
        }
    }
#endif
    
    return NO;
}

+ (BOOL)isValidEmojiString:(NSString *)string
{
    return [string isIncludingEmoji];
}

+ (double)notRounding:(double)price dis:(double)dis
{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundUp scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    
    NSDecimalNumber *ouncesDecimal;
    
    NSDecimalNumber *twoDecimal;
    
    NSDecimalNumber *roundedOunces;
    
    ouncesDecimal = [[NSDecimalNumber alloc] initWithDouble:price];
    
    twoDecimal = [[NSDecimalNumber alloc] initWithDouble:dis];
    
    NSDecimal p = ouncesDecimal.decimalValue;
    NSDecimal d = twoDecimal.decimalValue;
    
    NSDecimal accumulator;
    
    NSDecimalMultiply(&accumulator, &p, &d, NSRoundUp);
    
    NSDecimalNumber *pd = [[NSDecimalNumber alloc] initWithDecimal:accumulator];
    
    roundedOunces = [pd decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    
    NSString *str = [NSString stringWithFormat:@"%@",roundedOunces];
    return str.doubleValue;
}


#pragma mark - 金额的精确运算算法：加减乘除（重要）

+ (NSDecimalNumber *)vg_decimalNumberWithString:(NSString *)value1;
{
    return [NSDecimalNumber decimalNumberWithString:value1];
}

+ (NSString *)vg_decimalNumberMutiplyWithString:(NSString *)multiplierValue value2:(NSString *)multiplicandValue;
{
    NSDecimalNumber *multiplierNumber = [NSDecimalNumber decimalNumberWithString:multiplierValue];
    NSDecimalNumber *multiplicandNumber = [NSDecimalNumber decimalNumberWithString:multiplicandValue];
    NSDecimalNumber *product = [multiplicandNumber decimalNumberByMultiplyingBy:multiplierNumber];
    return [product stringValue];
}

+ (NSString *)vg_decimalNumberSubtractingWithString:(NSString *)value1 value2:(NSString *)value2;
{
    NSDecimalNumber *value1Number = [NSDecimalNumber decimalNumberWithString:value1];
    NSDecimalNumber *value2Number = [NSDecimalNumber decimalNumberWithString:value2];
    NSDecimalNumber *product = [value1Number decimalNumberBySubtracting:value2Number];
    return [product stringValue];
}

+ (NSString *)vg_decimalNumberAddingWithString:(NSString *)value1 value2:(NSString *)value2
{
    NSDecimalNumber *value1Number = [NSDecimalNumber decimalNumberWithString:value1];
    NSDecimalNumber *value2Number = [NSDecimalNumber decimalNumberWithString:value2];
    NSDecimalNumber *product = [value1Number decimalNumberByAdding:value2Number];
    return [product stringValue];
}

+ (NSString *)vg_decimalNumberDividingWithString:(NSString *)value1 value2:(NSString *)value2;
{
    NSDecimalNumber *value1Number = [NSDecimalNumber decimalNumberWithString:value1];
    NSDecimalNumber *value2Number = [NSDecimalNumber decimalNumberWithString:value2];
    NSDecimalNumber *product = [value1Number decimalNumberByDividingBy:value2Number];
    return [product stringValue];
}

#pragma mark - 动态计算行高
+ (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)textSize {
    CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:textSize]} context:nil];
    //返回计算出的行高
    return ceilf(rect.size.height);
}


@end
